/*
Kakine
ActionScript Framework
Copyright © 2011, PUNY, LLC.

This file is part of KAKINE.

KAKINE is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

KAKINE is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with KAKINE.  If not, see <http://www.gnu.org/licenses/>.
*/ 
package com.puny.utils
{
	import flash.net.URLLoader;
	import flash.utils.ByteArray;

	public class RectParser extends Object
	{
		private var _carrier:uint;
		private var _len:uint;
		private var _swf:ByteArray;
		private var _minX:uint;
		private var _minY:uint;
		private var _maxX:uint;
		private var _maxY:uint;
		public function RectParser(swf:ByteArray)
		{
			_swf = swf;
			var nbits:uint = readNbits();
			_minX = rect(nbits);
			_maxX = rect(nbits);
			_minY = rect(nbits);
			_maxY = rect(nbits);
			_swf = null;
		}

		public function get minX():uint
		{
			return _minX;
		}

		public function get minY():uint
		{
			return _minY;
		}

		public function get maxX():uint
		{
			return _maxX;
		}

		public function get maxY():uint
		{
			return _maxY;
		}

		private function readNbits():uint {
			var tmp:uint = _swf.readUnsignedByte();
			_len = 3;
			var nbits:uint = tmp >> _len;
			_carrier = tmp &(Math.pow(2,_len)-1);
			return nbits;
		}

		private function rect(nbits:uint):uint {
			var read:uint = nbits;
			var tmp2:uint = 0;
			var value:uint = _carrier;
			read -= _len;
			while( read > 0) {
				tmp2 = _swf.readUnsignedByte();
				if (read < 8) {
					_len = 8-read;
					value = value * Math.pow(2, read) + (tmp2 >> _len);
					_carrier = tmp2 & (Math.pow(2, _len)-1);
					read = 0;
				} else {
					value = value * 0x100 + tmp2;
					read -= 8;
					_len = 0;
					_carrier = 0;
				}
			}
			return value;
		}

	}
}